﻿/*
Autor...: Ivan M. Kruger
Empresa.: Home Kruger
Data....: 03/03/2011
*/

using System;
using System.IO;
using ik.ExtensionMethor;

namespace ik.FileSystem
{
    public class clFileSystem
    {
        #region "delegates - Sync files"
        //public delegate void SyncDelegateOnSkipped(Object sender, SkippedChangeEventArgs e);
        //public event SyncDelegateOnSkipped OnSkippedChangeSync;

        //public delegate void SyncDelegateOnApplied(Object sender, AppliedChangeEventArgs e);
        //public event SyncDelegateOnApplied OnAppliedChangeSync;

        //public delegate void SyncDelegateOnCopying(object sender, CopyingFileEventArgs e);
        //public event SyncDelegateOnCopying OnAppliedCopuingSync;
        #endregion

        #region "constructor"
        /// <summary>
        /// class constructor
        /// </summary>
        public clFileSystem()
        { }
        /// <summary>
        /// write text in text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">text to write</param>
        public clFileSystem(String path, String file, String text)
        {
            try
            {
                WriteFile(path, file, text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// write text in text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">text to write</param>
        public clFileSystem(String file, String text)
        {
            try
            {
                WriteFile(file, text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// write text in text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">array text to write</param>
        public clFileSystem(String path, String file, String[] text)
        {
            try
            {
                WriteFile(path, file, text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// write text in text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">array text to write</param>
        public clFileSystem(String file, String[] text)
        {
            try
            {
                WriteFile(file, text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "ToString"
        /// <summary>
        /// class information
        /// </summary>
        /// <returns>String</returns>
        public override String ToString()
        {
            return "Class name: ik.classFileSystem.clFileSystem \n\n" +
                   "Class version: " + Environment.Version.ToString() + "\n" +
                   "OS version: " + Environment.OSVersion.ToString() + "\n" +
                   "Computer name: " + Environment.MachineName + "\n" +
                   "Rights: (c) 2010 - by Ivan Kruger";
        }
        /// <summary>
        /// class information
        /// </summary>
        /// <mail>email information</mail>
        /// <returns>String</returns>
        public String ToString(Boolean email)
        {
            return "Class name: ik.classFileSystem.clFileSystem \n\n" +
                   "Class version: " + Environment.Version.ToString() + "\n" +
                   "OS version: " + Environment.OSVersion.ToString() + "\n" +
                   "Computer name: " + Environment.MachineName + "\n\n" +
                   "Rights: (c) 2010 - by Ivan Kruger \n" +
                   "eMail: ikruger@gmail.com";
        }
        #endregion

        #region "ExistsFile"
        /// <summary>
        /// check file exists
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <returns>Boolean</returns>
        public Boolean ExistsFile(String path, String file)
        {
            try
            {
                return ExistsFile(Path.Combine(CheckPath(path), file));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// check file exists
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <returns>Boolean</returns>
        public Boolean ExistsFile(String file)
        {
            try
            {
                return File.Exists(file);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "ExistsDirectory"
        /// <summary>
        /// verifica se existe a pasta
        /// </summary>
        /// <param name="path">path</param>
        /// <returns>Boolean</returns>
        public Boolean ExistsDirectory(String path, Boolean autoCreate)
        {
            try
            {
                Boolean _exists = new System.IO.DirectoryInfo(path).Exists;
                if (!_exists && autoCreate)
                {
                    new System.IO.DirectoryInfo(path).Create();
                    return true;
                }
                return _exists;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "CreateFile"
        /// <summary>
        /// create a text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <exception cref=">IOException"
        /// <returns>Boolean</returns>
        public Boolean CreateFile(String path, String file)
        {
            try
            {
                return CreateFile(Path.Combine(CheckPath(path), file));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// create a text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <returns>Boolean</returns>
        public Boolean CreateFile(String file)
        {
            try
            {
                new StreamWriter(file, false);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "WriteFile"
        /// <summary>
        /// write text in text file. NOTE: override if exists file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">text to write</param>
        /// <returns>Boolean</returns>
        public Boolean WriteFile(String path, String file, String text)
        {
            try
            {
                return WriteFile(Path.Combine(CheckPath(path), file), text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// write text in text file. NOTE: override if exists file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">text to write</param>
        /// <returns>Boolean</returns>
        public Boolean WriteFile(String file, String text)
        {
            try
            {
                File.WriteAllText(file, text);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// write text in text file. NOTE: override if exists file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">array text to write</param>
        /// <example>
        /// String[] lines = {"First line", "Second line", "Third line"};
        /// WriteFile("c:", "MyFile.txt", lines);
        /// </example>
        /// <returns>Boolean</returns>
        public Boolean WriteFile(String path, String file, String[] text)
        {
            try
            {
                return WriteFile(Path.Combine(CheckPath(path), file), text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// write text in text file. NOTE: override if exists file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">array text to write</param>
        /// String[] lines = {"First line", "Second line", "Third line"};
        /// WriteFile("c:\MyFile.txt", lines);
        /// <returns>Boolean</returns>
        public Boolean WriteFile(String file, String[] text)
        {
            try
            {
                File.WriteAllLines(@file, text);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "AppendFile"
        /// <summary>
        /// append text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">text to write</param>
        /// <returns>Boolean</returns>
        public Boolean AppendFile(String path, String file, String text)
        {
            try
            {
                return AppendFile(Path.Combine(CheckPath(path), file), text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// append text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">text to write</param>
        /// <returns>Boolean</returns>
        public Boolean AppendFile(String file, String text)
        {
            try
            {
                StreamWriter _sw = new StreamWriter(file, true);
                _sw.WriteLine(text);
                _sw.Close();
                _sw = null;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// append text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <param name="text">array text to write</param>
        /// <returns>Boolean</returns>
        public Boolean AppendFile(String path, String file, String[] text)
        {
            try
            {
                return AppendFile(Path.Combine(CheckPath(path), file), text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// append text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <param name="text">array text to write</param>
        /// <returns>Boolean</returns>
        public Boolean AppendFile(String file, String[] text)
        {
            try
            {
                StreamWriter _sw = new StreamWriter(file, true);
                foreach (String line in text)
                    _sw.WriteLine(line);
                _sw.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "EraseFile"
        /// <summary>
        /// erase text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <returns>Boolean</returns>
        public Boolean EraseFile(String file)
        {
            try
            {
                if (ExistsFile(file))
                    File.Delete(file);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// erase text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <returns>Boolean</returns>
        public Boolean EraseFile(String path, String file)
        {
            try
            {
                return EraseFile(Path.Combine(CheckPath(path), file));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "CopyFile"
        /// <summary>
        /// copy text file
        /// </summary>
        /// <param name="fileSource">path and file source</param>
        /// <param name="fileTarget">path and file target</param>
        /// <returns>Boolean</returns>
        public Boolean CopyFile(String fileSource, String fileTarget)
        {
            try
            {
                if (ExistsFile(fileSource))
                {
                    File.Copy(fileSource, fileTarget, true);
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// copy text file
        /// </summary>
        /// <param name="pathSource">path source</param>
        /// <param name="fileSource">file source</param>
        /// <param name="pathTarget">path target</param>
        /// <param name="fileTarget">file target</param>
        /// <returns>Boolean</returns>
        public Boolean CopyFile(String pathSource, String fileSource, String pathTarget, String fileTarget)
        {
            try
            {
                return CopyFile(Path.Combine(pathSource, fileSource), Path.Combine(CheckPath(pathTarget), CheckPath(fileTarget)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "MoveFile"
        /// <summary>
        /// Move text file
        /// </summary>
        /// <param name="fileSource">path and file source</param>
        /// <param name="fileTarget">path and file target</param>
        /// <returns>Boolean</returns>
        public Boolean MoveFile(String fileSource, String fileTarget)
        {
            try
            {
                if (ExistsFile(fileSource))
                {
                    File.Move(fileSource, fileTarget);
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Move text file
        /// </summary>
        /// <param name="pathSource">path source</param>
        /// <param name="fileSource">file source</param>
        /// <param name="pathTarget">path target</param>
        /// <param name="fileTarget">file target</param>
        /// <returns>Boolean</returns>
        public Boolean MoveFile(String pathSource, String fileSource, String pathTarget, String fileTarget)
        {
            try
            {
                return MoveFile(Path.Combine(pathSource, fileSource), Path.Combine(CheckPath(pathTarget), CheckPath(fileTarget)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "CheckPath"
        /// <summary>
        /// check path is correct
        /// </summary>
        /// <param name="path">path</param>
        /// <returns>String</returns>
        private String CheckPath(String path)
        {
            try
            {
                //return path += path.LastIndexOf(@"\") == -1 ? @"\" : "";
                return path += path.Substring(path.Length - 1, 1) != @"\" ? @"\" : "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "ReaderFile"
        /// <summary>
        /// erase text file
        /// </summary>
        /// <param name="file">path and filename</param>
        /// <returns>TextReader</returns>
        public TextReader ReaderFile(String file)
        {
            try
            {
                if (ExistsFile(file))
                    return new StreamReader(file);
                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// erase text file
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="file">filename</param>
        /// <returns>TextReader</returns>
        public TextReader ReaderFile(String path, String file)
        {
            try
            {
                if (ExistsFile(path, file))
                    return ReaderFile(Path.Combine(CheckPath(path), file));

                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "GetFiles"
        /// <summary>
        /// retorna os arquivos existentes numa pasta
        /// </summary>
        /// <param name="path">caminho</param>
        /// <param name="filter">filtro</param>
        /// <returns>FileInfo[]</returns>
        public FileInfo[] GetFiles(String path, String filter)
        {
            try
            {
                return new DirectoryInfo(path).GetFiles(filter);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "GetFilesString"
        /// <summary>
        /// retorna os arquivos existentes numa pasta
        /// </summary>
        /// <param name="path">caminho</param>
        /// <param name="filter">filtro</param>
        /// <returns>String[]</returns>
        public String[] GetFilesString(String path, String filter)
        {
            try
            {
                String[] _str = new String[0];
                foreach (FileInfo f in GetFiles(path, filter))
                {
                    _str = ik.Functions.clFunctions.ArrayChange(_str);
                    _str[_str.Length - 1] = f.Name;
                }
                return _str;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "CreateFolder"
        /// <summary>
        /// cria uma pasta caso ela não exista
        /// </summary>
        /// <param name="path">caminho</param>
        /// <returns>Boolean</returns>
        public Boolean CreateFolder(String path)
        {
            try
            {
                Boolean _ret = new DirectoryInfo(path).Exists;
                if (!_ret)
                    new DirectoryInfo(path).Create();
                return _ret;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "FileRename"
        /// <summary>
        /// renomear um arquivo
        /// </summary>
        /// <param name="path">path and file</param>
        /// <returns>Boolean</returns>
        public Boolean FileRename(String path, String file, String newName)
        {
            try
            {
                if (ExistsFile(path, file))
                {
                    new FileInfo(CheckPath(path)).Replace(newName, "_" + newName);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "FindFolder"
        /// <summary>
        /// utilizado num botao para buscar uma determinada pasta...
        /// </summary>
        /// <param name="tb">nome do textbox para retorno da pasta selecionada</param>
        /// <returns>Boolean</returns>
        public static Boolean FindFolder(System.Windows.Forms.TextBox tb)
        {
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
            try
            {
                if (tb.Text != "")
                    fbd.SelectedPath = tb.Text;

                System.Windows.Forms.DialogResult _res = fbd.ShowDialog();
                if (_res == System.Windows.Forms.DialogResult.OK)
                {
                    tb.Text = fbd.SelectedPath;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "GetDirectories"
        /// <summary>
        /// retorna os diretorios existentes a partir de uma pasta
        /// </summary>
        /// <param name="path">caminho</param>
        /// <param name="searchPattern">filtro.   ex: "*"</param>
        /// <param name="option">parametros da pesquisa</param>
        /// <returns>coleção de Strings</returns>
        public String[] GetDirectories(String path, String searchPattern, SearchOption option)
        {
            try
            {
                return Directory.GetDirectories(path, searchPattern, option);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "FileCompare"
        /// <summary>
        /// compara se dois arquivos são iguais
        /// </summary>
        /// <param name="file1">arquivo</param>
        /// <param name="file2">arquivo</param>
        /// <returns>Boolean</returns>
        public Boolean FileCompare(String file1, String file2)
        {
            Int32 file1byte;
            Int32 file2byte;
            FileStream fs1;
            FileStream fs2;

            if (file1 == file2)
            {
                return true;
            }

            // Open the two files.
            fs1 = new FileStream(file1, FileMode.Open);
            fs2 = new FileStream(file2, FileMode.Open);

            // Check the file sizes. If they are not the same, the files 
            // are not the same.
            if (fs1.Length != fs2.Length)
            {
                fs1.Close();
                fs2.Close();
                return false;
            }

            // Read and compare a byte 
            do
            {
                file1byte = fs1.ReadByte();
                file2byte = fs2.ReadByte();
            }
            while ((file1byte == file2byte) && (file1byte != -1));

            // Close the files.
            fs1.Close();
            fs2.Close();
            return ((file1byte - file2byte) == 0);
        }
        #endregion
    }
}
